# stats.py
from datetime import datetime, timedelta, timezone
from database import get_timers
from dateutil.parser import parse
import math

class StatsAnalyzer:
    def __init__(self):
        self.records = self._load_records()
        self.has_special_time = self._check_special_time()

    def _load_records(self):
        records = []
        beijing_tz = timezone(timedelta(hours=8))
        for (_, h, m, s, created_at) in get_timers():
            try:
                # 解析带有时区的时间对象
                parsed_dt = parse(str(created_at))
                normalized_dt = parsed_dt.astimezone(beijing_tz)
                
                # 生成无时区的时间字符串（基于北京时间）
                beijing_naive = normalized_dt.replace(tzinfo=None).strftime("%Y-%m-%d %H:%M:%S")
                records.append((h * 3600 + m * 60 + s, beijing_naive))

            except Exception as e:
                print(f"解析时间失败: {e}")
        return records

    def _check_special_time(self):
        """检查是否存在特定时间记录 (00:10:30)"""
        for _, h, m, s, _ in get_timers():
            if h == 0 and m == 10 and s == 30:
                # print("发现特殊时间记录: 00:10:30")
                return True
        return False


    def get_weekly_stats(self):
        """按周统计"""
        weekly_data = {}
        for seconds, created_str in self.records:
            created = datetime.strptime(created_str, "%Y-%m-%d %H:%M:%S")
            year, week, _ = created.isocalendar()

            # 计算周范围（ISO标准周：周一 ~ 周日）
            start_date = datetime.fromisocalendar(year, week, 1).strftime("%Y-%m-%d")
            end_date = datetime.fromisocalendar(year, week, 7).strftime("%Y-%m-%d")
            
            week_key = f"{year}-W{week:02d}：{start_date}~{end_date}"
            weekly_data[week_key] = weekly_data.get(week_key, 0) + seconds
        return weekly_data

    def get_duration_data(self, start_date=None, end_date=None):
        """获取原始时长数据"""
        # 使用与get_heatmap_data相同的初始化逻辑
        if not start_date:
            start_date = datetime.now() - timedelta(days=181)
        if not end_date:
            end_date = datetime.now()

        daily_data = {}
        current_date = start_date.date()
        end_date = end_date.date()
        while current_date <= end_date:
            daily_data[current_date] = 0
            current_date += timedelta(days=1)

        # 填充实际数据
        # print(self.records)
        for seconds, created_str in self.records:
            try:
                created = datetime.strptime(created_str, "%Y-%m-%d %H:%M:%S").date()
                if start_date.date() <= created <= end_date:
                    daily_data[created] += seconds
            except Exception as e:
                print(f"无效日期格式: {created_str}")
        # print (daily_data)
        return daily_data  # 返回 {日期: 总秒数}
        

    def get_color_mapping(self, start_date=None, end_date=None):
        """获取颜色映射数据"""
        
        # 原有的热力图逻辑
        duration_data = self.get_duration_data(start_date, end_date)
        max_seconds = 12 * 3600
        color_gradient = [
            "#ebedf0",  # 0小时
            "#9be9a8",  # 1级
            "#40c463",  # 2级
            "#30a14e",  # 3级
            "#216e39"   # 4级
        ]
        return {
            date: self._calculate_color_gradient(seconds, max_seconds, color_gradient)
            for date, seconds in duration_data.items()
        }

    def _calculate_color_gradient(self, seconds, max_seconds, gradient):
        """计算颜色梯度"""
        if seconds == 0:
            return gradient[0]
        
        # 将时长转换为梯度等级（1-4）
        ratio = seconds / max_seconds
        level = min(4, max(1, int(ratio * 4) + 1))
        return gradient[level]

    @staticmethod
    def format_duration(seconds):
        """格式化时间显示"""
        hours = seconds // 3600
        minutes = (seconds % 3600) // 60
        return f"{hours}h {minutes}m"